package com.holystone.orca.itsm.shiro;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用户权限不足是使用AuthorizationFilter进行拦截处理的，我们依然可以重写里面的onAccessDenied方法
 *  AuthorizationFilter抽象类事项了javax.servlet.Filter接口，它是个过滤器。
 * 为自定义的filter ,作用是角色权限设置成或者的关系，shiro自带的roles为并且关系，不符合要要求。
 */
public class RolesOrAuthFilter extends AuthorizationFilter {
    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        String[] rolesArray = (String[]) mappedValue;
        if (rolesArray == null || rolesArray.length == 0) {
            return true;
        }
        for (String aRolesArray : rolesArray) {
            if (subject.hasRole(aRolesArray)) {
                return true;
            }
        }
        return false;
    }
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse) response;

        String id = WebUtils.toHttp(request).getParameter(MySessionManager.AUTHORIZATION);
        //如果请求头中有 Authorization 则其值为sessionId
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        JSONObject result = new JSONObject();
        //前端Ajax请求，则不会重定向
        resp.setHeader("Access-Control-Allow-Origin",  req.getHeader("Origin"));
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setContentType("application/json; charset=utf-8");
        resp.setCharacterEncoding("UTF-8");
        JSONObject data = new JSONObject();
        if(req.getSession(false)==null){
            result.put("msg", "请登陆！");
            data.put("code",403);
            result.put("data", data);
        }else if (!StringUtils.isEmpty(id)) {
            result.put("msg", "权限不足！");
            data.put("code",401);
            result.put("data", data);
        }else{
            result.put("msg", "请登陆！");
            data.put("code",400);
            result.put("data", data);
        }
            out.println(result.toJSONString());
            out.flush();
            out.close();
        return false;

    }
}